<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace CZTools\Hyperf\Exceptions\Handler;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Exception\HttpException;
use Hyperf\HttpMessage\Exception\MethodNotAllowedHttpException;
use Hyperf\HttpMessage\Exception\NotFoundHttpException;
use Hyperf\HttpMessage\Exception\ServerErrorHttpException;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class RouteExceptionHandler extends ExceptionHandler
{
    /**
     * @var StdoutLoggerInterface
     */
    protected $logger;

    public function __construct(StdoutLoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function handle(Throwable $throwable, ResponseInterface $response)
    {
//      判断被捕获到的异常是希望被捕获的异常
        $error_msg = '';

        if ($throwable instanceof HttpException) {
            if ($throwable instanceof NotFoundHttpException) {
                $request = ApplicationContext::getContainer()->get(RequestInterface::class);
                $pathInfo = explode('/', $request->getPathInfo());
                $error_msg = '方法不存在 ' . (count($pathInfo) > 1 ? $pathInfo[count($pathInfo) - 1] : '') . ' ' . $throwable->getMessage();
            } else if ($throwable instanceof MethodNotAllowedHttpException) {
                $error_msg = "请求方式错误 " . $throwable->getMessage();
            } else if ($throwable instanceof ServerErrorHttpException) {
                $error_msg = '服务错误：' . $throwable->getMessage();
            } else {
                $error_msg = 'http请求错误:' . $throwable->getMessage();
            }
        }

        if ($error_msg) {
            // 格式化输出
            $data = json_encode([
                'code' => 500,
                'message' => $error_msg,
            ], JSON_UNESCAPED_UNICODE);

            // 阻止异常冒泡
            $this->stopPropagation();
            $this->logger->error(sprintf('%s[%s] in %s', $throwable->getMessage(), $throwable->getLine(), $throwable->getFile()));
            $this->logger->error($throwable->getTraceAsString());

            return $response->withStatus(200)->withBody(new SwooleStream($data));
        }

        // 交给下一个异常处理器
        return $response;

        // 或者不做处理直接屏蔽异常
    }

    /**
     * @inheritDoc
     */
    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}